<template>
  <div class="register-form">
    <h2 class="form-title">公众注册</h2>
    <el-form :model="form" :rules="rules" ref="registerFormRef">
      <el-form-item prop="username">
        <el-input v-model="form.username" placeholder="用户名" :prefix-icon="User" size="large" />
      </el-form-item>

      <el-form-item prop="password">
        <el-input v-model="form.password" type="password" placeholder="密码" :prefix-icon="Lock" size="large"
          show-password />
      </el-form-item>

      <el-form-item prop="confirmPassword">
        <el-input v-model="form.confirmPassword" type="password" placeholder="确认密码" :prefix-icon="Lock" size="large"
          show-password />
      </el-form-item>

      <el-form-item prop="phone">
        <el-input v-model="form.phone" placeholder="手机号" :prefix-icon="Iphone" size="large" />
      </el-form-item>

      <el-form-item prop="email">
        <el-input v-model="form.email" placeholder="邮箱" :prefix-icon="Message" size="large" />
      </el-form-item>

      <el-form-item prop="realName">
        <el-input v-model="form.realName" placeholder="真实姓名" :prefix-icon="Edit" size="large" />
      </el-form-item>

      <el-form-item prop="idCard">
        <el-input v-model="form.idCard" placeholder="身份证号" :prefix-icon="CreditCard" size="large" />
      </el-form-item>

      <el-form-item prop="avatar">
        <el-upload class="avatar-uploader" action="#" :show-file-list="false" :on-change="handleAvatarChange"
          :auto-upload="false">
          <img v-if="form.avatar" :src="form.avatar" class="avatar">
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
        <div class="upload-tip">点击上传头像</div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" size="large" @click="submitForm" style="width: 100%">
          注册
        </el-button>
      </el-form-item>

      <div class="form-footer">
        <el-link type="primary" @click="emit('switch-form', 'LoginForm')">
          返回登录
        </el-link>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Lock, Iphone, Message, Edit, CreditCard, Plus } from '@element-plus/icons-vue'
import { UserApi } from '@/api/user'

const emit = defineEmits(['switch-form', 'register-success'])

const registerFormRef = ref(null)

const form = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  phone: '',
  email: '',
  realName: '',
  idCard: '',
  avatar: ''
})

const validatePass2 = (rule, value, callback) => {
  if (value !== form.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const validatePhone = (rule, value, callback) => {
  const phoneReg = /^1[3-9]\d{9}$/
  if (!value) {
    callback(new Error('请输入手机号'))
  } else if (!phoneReg.test(value)) {
    callback(new Error('请输入正确的手机号'))
  } else {
    callback()
  }
}

const validateIdCard = (rule, value, callback) => {
  const idCardReg = /^\d{17}[\dXx]$/
  if (!value) {
    callback(new Error('请输入身份证号'))
  } else if (!idCardReg.test(value)) {
    callback(new Error('请输入正确的身份证号'))
  } else {
    callback()
  }
}

const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 16, message: '长度在 4 到 16 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePass2, trigger: 'blur' }
  ],
  phone: [
    { validator: validatePhone, trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  idCard: [
    { validator: validateIdCard, trigger: 'blur' }
  ]
})

const handleAvatarChange = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    form.avatar = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

const submitForm = async () => {
  try {
    await registerFormRef.value.validate()

    await UserApi.registerPublic(form)
    ElMessage.success('注册成功,请登录')
    emit('switch-form', 'LoginForm')

  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.error('注册失败，请检查输入信息')
  }
}
</script>

<style scoped>
.register-form {
  position: relative;
  z-index: 1;
}

.form-title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
  font-weight: 600;
  font-size: 24px;
}

.avatar-uploader {
  display: flex;
  justify-content: center;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.3s;
}

.avatar-uploader-icon:hover {
  border-color: #409eff;
}

.upload-tip {
  text-align: center;
  color: #999;
  font-size: 12px;
  margin-top: 5px;
}

.form-footer {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}
</style>